package com.sntk.organauthomanager.application.service;

import com.sntk.organauthomanager.application.dto.LoginUser;
import com.sntk.organauthomanager.application.dto.OperatorInfo;
import com.sntk.organauthomanager.domain.model.Organization;
import com.sntk.organauthomanager.domain.model.User;
import com.sntk.organauthomanager.domain.model.UserAffiliate;
import com.sntk.organauthomanager.domain.repository.OrganizationRepository;
import com.sntk.organauthomanager.domain.repository.UserAffiliateRepository;
import com.sntk.organauthomanager.domain.repository.UserRepository;
import com.sntk.organauthomanager.infrastructure.exception.DataNoLegalException;
import com.sntk.organauthomanager.infrastructure.exception.ObjectNotFoundException;
import com.sntk.organauthomanager.infrastructure.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * @ClassName: LoginApplicationService
 * @author: wgchao
 * @createTime: 2020/8/5 10:07 AM
 * @Description: TODO
 */
@Service
@Transactional(readOnly = true)
public class LoginApplicationService {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private OrganizationRepository organizationRepository;
    @Autowired
    private UserAffiliateRepository userAffiliateRepository;
    @Autowired
    private JwtUtil jwtUtil;

    public String applyAccessToken(LoginUser loginUser){
        User user = userRepository.findByKey(loginUser.getUname());
        if(user == null){
            throw new ObjectNotFoundException("账户不存在");
        }
        user.normalException();
        String institutionNumber = user.getInstitutionNumber();
        //指定登陆机构-检校机构合法性
        if(!StringUtils.isEmpty(loginUser.getInstitutionNumber())){
            institutionNumber = loginUser.getInstitutionNumber();
            if(loginUser.getInstitutionNumber().equals(user.getInstitutionNumber())){

            }else{
                UserAffiliate userAffiliate = userAffiliateRepository.findByKey(loginUser.getUname());
                if(userAffiliate.isAffiliates(loginUser.getInstitutionNumber())){

                }else{
                    throw new DataNoLegalException("账户未关联该机构");
                }
            }
        }

        if(userRepository.matchPassword(loginUser.getPassword(), user.getPassword())){
            //密码匹配-生成token
            String accessToken = jwtUtil.createJWT(user.getUname(), institutionNumber, "local");
            return accessToken;
        }else{
            //密码不匹配
            throw new DataNoLegalException("账户密码错误");
        }
    }

    /**
     * 解析token并获取user信息
     * @param token
     * @return
     */
    public OperatorInfo autho(String token){
        Claims claims = jwtUtil.parseJWT(token);
        if(claims == null){//token解析错误
            throw new RuntimeException("验证信息无效！");
        }
        String uname = claims.getId();
        User user = userRepository.findByKey(uname);
        if(user == null){
            throw new ObjectNotFoundException("账户不存在");
        }
        user.normalException();

        Organization organization = organizationRepository.findByKey(claims.getSubject());

        return new OperatorInfo(user.getUname(), user.getUserName(),
                claims.getSubject(), organization.getInstitutionName(), user.getUserType().getIndex());
    }
}
